package com.frontop.terminal.component;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.constant.CommandConst;
import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.constant.PlayStatusConst;
import com.frontop.terminal.entity.Message;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.gangedsocket.core.PlayGangedClient;
import com.frontop.terminal.gangedsocket.core.PlayGangedServiceSocket;
import com.frontop.terminal.model.bo.TerminalConfigBo;
import com.frontop.terminal.service.impl.PlayListServiceImpl;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.SystemMonitoringUtil;
import com.frontop.terminal.util.WriteDataUtil;
import com.frontop.terminal.vlcjplayer.VlcjPlayer;

import java.util.Objects;

import static com.frontop.terminal.vlcjplayer.Application.application;

/**
 * <p>
 * 启动时执行初始化
 * </P>
 *
 * @author :CCC
 * @since :2021-06-09
 **/
public class StartTask {

    /**
     * 初始化核心组件
     */
    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    public static void init() {
        ReadDataUtil.init();
        TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();
        assert terminalConfig != null;
        //获取服务器配置 TODO 待优化
//        getServerConfig(terminalConfig);

        //播放联动是否开启
        playerGanged(terminalConfig);

        //异步线程启动浏览器
        ThreadUtil.execAsync(new Browser());

        //获取播放任务
        ThreadUtil.execAsync(new Thread(() -> {
            ThreadUtil.sleep(16000);
            new PlayListServiceImpl().executeWork(new Message().setCommand(CommandConst.REFRESH));
        }));

        //播放器
        startVlcPlay(terminalConfig);
    }

    /**
     * 播放联动是否开启
     *
     * @param terminalConfig 终端配置对象
     */
    private static void playerGanged(TerminalConfig terminalConfig) {
        if (terminalConfig.isPlayerGanged()) {
            //本机作为服务端
            if (terminalConfig.isPlayerGangedServer()) {
                PlayGangedServiceSocket.start();
            }
            //本机作为客户端
            if (terminalConfig.isPlayerGangedClient()) {
                PlayGangedClient.start();
            }
        }
    }

    private static void startVlcPlay(TerminalConfig terminalConfig) {
        //播放器启动状态
        boolean vlcStatus = true;

        while (vlcStatus) {
            if (Objects.nonNull(terminalConfig.getStatus()) && terminalConfig.getStatus()) {
                VlcjPlayer.setLookAndFeel();
                VlcjPlayer app = new VlcjPlayer();
                app.start();
                vlcStatus = false;

                //播放器隐藏
                if (terminalConfig.isPlayerHide()) {
                    VlcjPlayer.vlcPlayerVisible(false);
                } else {
                    VlcjPlayer.vlcPlayerVisible(true);
                    //播放器全屏
                    //播放器全屏前提条件组件必须可见的
                    VlcjPlayer.vlcPlayerFullScreen(terminalConfig.isPlayerFullScreen());
                }

                //播放模式单个循环的话
                if (terminalConfig.getPlayMode().equals(PlayStatusConst.PLAYP_PATTERN_ON)) {
                    //设置播放器重复播放状态
                    application().mediaPlayer().controls().setRepeat(true);
                }

                //休眠两秒让程序处理数据完成
                ThreadUtil.sleep(2000);

                //启动后是否自动播放视频，前提是播放器不隐藏
                if (!terminalConfig.isPlayerHide() && terminalConfig.isAutoPlay()) {
                    //获取播放文件位置
                    String resourcePath = ResourcePublishing.getResource();
                    System.out.println("播放器启动完成,即将自动播放资源");
                    VlcjPlayer.play(resourcePath);
                }

                //启用了待机画面，前提是播放器不隐藏并且未启用开机自动播放选项
                if (!terminalConfig.isPlayerHide() && !terminalConfig.isAutoPlay() && terminalConfig.isEnableStandby()) {
                    //获取待机资源
                    String standbyResource = ResourcePublishing.getStandbyResource();
                    //播放
                    VlcjPlayer.play(standbyResource);
                }

            }

        }
    }


    /**
     * 获取服务器配置
     */
    private static void getServerConfig(@org.jetbrains.annotations.NotNull TerminalConfig terminalConfig) {
        String mac = SystemMonitoringUtil.getMacAddress();
        //获取服务器配置地址拼装完整接口
        String url = terminalConfig.getServerAddress() + InterfaceConst.GET_TERMINAL_CONFIG;
        String result;

        try {
            result = HttpRequest.get(url)
                    //设置连接超时和响应超时时间
                    .timeout(3000)
                    .header(HeaderEnum.TERMINAL_TOKEN.getKey(), Objects.requireNonNull(ReadDataUtil.getTerminalConfig()).getAuthorizationCode())
                    .form("mac", mac).execute().body();

            System.out.println("收到服务器最新配置:" + result);

            TerminalConfigBo terminalConfigBo = JSON.parseObject(result, TerminalConfigBo.class);
            if (Objects.nonNull(terminalConfigBo)) {
                terminalConfig.setPlayMode(terminalConfigBo.getPlayMode());
                terminalConfig.setPlayerHide(terminalConfigBo.getHide());
                terminalConfig.setBrowserFullScreen(terminalConfigBo.getFullScreen());
                terminalConfig.setPlayerLastFrame(terminalConfigBo.getLastFrame());
                terminalConfig.setAutoPlay(terminalConfigBo.getAutoPlay());
                terminalConfig.setBrowserHide(terminalConfigBo.getBrowserHide());
                //保存配置
                WriteDataUtil.write(terminalConfig, ReadDataUtil.TERMINAL_CONFIG_CODING);
            }

        } catch (IORuntimeException ignored) {
        } catch (NullPointerException e) {
            System.out.println("获取服务器配置过程中返回值为空");
        } catch (NumberFormatException e) {
            System.out.println("获取服务器配置过程中返回值异常");
        } catch (Exception e) {
            System.out.println("获取服务器配置出现未知异常");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        VlcjPlayer.setLookAndFeel();
        VlcjPlayer app = new VlcjPlayer();
        app.start();

        VlcjPlayer.vlcPlayerVisible(true);
        application().mediaPlayer().fullScreen().set(true);

        //播放
        application().mediaPlayer().media().play("C:\\Users\\hasee\\Desktop\\惠阳双中心序厅_2560-880.mp4");

        application().mediaPlayer().video().setAdjustVideo(true);
        application().mediaPlayer().video().setAspectRatio("1:1");
        application().mediaPlayer().video().setScale(0);
        System.out.println("视频宽高比：" + application().mediaPlayer().video().aspectRatio());
        System.out.println("视频调整器是否开启：" + application().mediaPlayer().video().isAdjustVideo());
    }
}
